package com.xiaoma.tpo.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.xiaoma.tpo.dao.ClsClassDao;
import com.xiaoma.tpo.dao.ClsCourseDao;
import com.xiaoma.tpo.dao.ClsCoursePrizeDao;
import com.xiaoma.tpo.dao.ClsCourseVedioDao;
import com.xiaoma.tpo.dao.ClsGateDao;
import com.xiaoma.tpo.dao.ClsGateSentenceDao;
import com.xiaoma.tpo.dao.ClsListeningDao;
import com.xiaoma.tpo.dao.ClsListeningQuestionDao;
import com.xiaoma.tpo.dao.ClsScoreDao;
import com.xiaoma.tpo.dao.ClsSentenceDao;
import com.xiaoma.tpo.dao.ClsUserClassDao;
import com.xiaoma.tpo.dao.ClsWordDao;
import com.xiaoma.tpo.domain.ClsClass;
import com.xiaoma.tpo.domain.ClsCourse;
import com.xiaoma.tpo.domain.ClsCoursePrize;
import com.xiaoma.tpo.domain.ClsCourseVideo;
import com.xiaoma.tpo.domain.ClsGate;
import com.xiaoma.tpo.domain.ClsGateSentence;
import com.xiaoma.tpo.domain.ClsListeningQuestion;
import com.xiaoma.tpo.domain.ClsScore;
import com.xiaoma.tpo.domain.ClsSentence;
import com.xiaoma.tpo.domain.ClsUserClass;
import com.xiaoma.tpo.domain.ClsWord;
import com.xiaoma.tpo.dto.ClsClassVo;
import com.xiaoma.tpo.dto.ClsCourseGateVo;
import com.xiaoma.tpo.dto.ClsCourseVo;
import com.xiaoma.tpo.dto.ClsGateScoreDto;
import com.xiaoma.tpo.dto.ClsSentenceVo;
import com.xiaoma.tpo.utils.Pager;
import com.xiaoma.tpo.utils.UploadImgUtil;

@Service
public class ClassService {

    @Autowired
    private ClsClassDao classDao;
    
    @Autowired
    private ClsCourseDao courseDao;
    
    @Autowired
    private ClsUserClassDao userClassDao;
    
    @Autowired
    private ClsWordDao wordDao;
    
    @Autowired
    private ClsSentenceDao sentenceDao;
    
    @Autowired
    private ClsScoreDao scoreDao;
    
    @Autowired
    private ClsGateDao gateDao;

    @Autowired
    private ClsCourseVedioDao courseVedioDao;
    
    @Autowired
    private ClsListeningDao listeningDao;
    
    @Autowired
    private ClsListeningQuestionDao listeningQuestionDao;

    @Autowired
    private ClsGateSentenceDao clsGateSentenceDao;
    
    @Autowired
    private ClsCoursePrizeDao coursePrizeDao;
    
//    @Autowired
//    private ClsAchievementBonusRecordDao clsAchievementBonusRecordDao;
    
    public List<ClsClassVo> findAllClasses() {
        return classDao.findAllWithUserCount();
    }
    public List<ClsClassVo> findAllClassesNoForecast() {
    	return classDao.findAllWithUserCountNoForecast();
    }
    
    public int findUserClassCountByClassId(int classId) {
        ClsUserClass entity = new ClsUserClass();
        entity.setClsClassId(classId);
        return userClassDao.queryCount(entity);
    }
    
    public ClsClass findClassById(int classId) {
        return classDao.getById(classId);
    }
    
    public List<ClsCourseVo> findCoursesByClassId(int classId) {
        List<ClsCourseGateVo> cgvos = courseDao.findCoursesByClassId(classId);
        List<ClsCourseVo> courses = new ArrayList<ClsCourseVo>();
        int preCourseId = 0;
        ClsCourseVideo ccv = null;
        for (ClsCourseGateVo vo : cgvos) {
            if (preCourseId != vo.getId()) {
                ccv = new ClsCourseVideo();
                ccv.setClsCourseId(vo.getId());
                ClsCourseVo courseVo = new ClsCourseVo();
                courseVo.setId(vo.getId());
                courseVo.setClassId(vo.getClsClassId());
                courseVo.setDesc(vo.getDesc());
                courseVo.setName(vo.getName());
                courseVo.setVideos(courseVedioDao.findByColumns(ccv));
                courseVo.setListening(listeningDao.findByCourseId(vo.getId()));
                List<ClsGate> gates = new ArrayList<ClsGate>();
                courseVo.setGates(gates);
                courses.add(courseVo);
            }
            ClsGate gate = new ClsGate();
            gate.setAudioZip(vo.getGateAudioZip());
            gate.setClsCourseId(vo.getId());
            gate.setDesc(vo.getGateDesc());
            gate.setId(vo.getGateId());
            gate.setName(vo.getGateName());
            gate.setType(vo.getGateType());
            gate.setSeqNum(vo.getGateSeqNum());
            courses.get(courses.size() - 1).getGates().add(gate);
            preCourseId = vo.getId();
            
        }
        return courses;
    }
    
    
    
    public int saveUserClass(ClsUserClass userClass) {
        return userClassDao.insert(userClass);
    }
    
    
    public ClsUserClass findUserClassByUserIdAndClassId(int userId, int classId) {
        ClsUserClass entity = new ClsUserClass();
        entity.setClsClassId(classId);
        entity.setUserId(userId);
        List<ClsUserClass> userClasses = userClassDao.findByColumns(entity);
        return userClasses.size() > 0 ? userClasses.get(0) : null;
    }
    
    public List<ClsUserClass> findUserClassByUserId(int userId) {
        ClsUserClass entity = new ClsUserClass();
        entity.setUserId(userId);
        return  userClassDao.findByColumns(entity);
    }
    
    public ClsScore findScore(int classId, int courseId, int gateId,int userId) {
        ClsScore entity = new ClsScore();
        entity.setClsClassId(classId);
        entity.setClsCourseId(courseId);
        entity.setClsGateId(gateId);
        entity.setUserId(userId);
        List<ClsScore> clsScores = scoreDao.findByColumns(entity);
        return clsScores.size() > 0 ? clsScores.get(0) : null;
    }
    
    public int saveScore(ClsScore clsScore) {
        return scoreDao.insert(clsScore);
    }
    
    public int updateScore(ClsScore clsScore) {
        return scoreDao.update(clsScore);
    }
    
    public List<ClsGateScoreDto> findScoresByClassIdAndUserId(int classId, int userId) {
        return scoreDao.findScoresByClassIdAndUserId(classId, userId);
    }
    
    public ClsGate findGateById(int gateId) {
        return gateDao.getById(gateId);
    }
    
    public List<ClsWord> findWordsByGateId(int gateId) {
        ClsWord entity = new ClsWord();
        entity.setClsGateId(gateId);
        return wordDao.findByColumns(entity);
    }
    
    public List<ClsSentence> findSentencesByGateId(int gateId) {
        return sentenceDao.findSentencesByGateId(gateId);
    }
    
    public List<ClsListeningQuestion> findListeningQuestions(int listeningId) {
        ClsListeningQuestion entity = new ClsListeningQuestion();
        entity.setClsListeningId(listeningId);
        return listeningQuestionDao.findByColumns(entity);
    }


    public List<ClsClass> getClassList(){
        List<ClsClass> list = classDao.findAll();
        return list;
    }

    public boolean addClass(MultipartFile file,ClsClassVo cvo){
    	String url = uploadImage(file);
    	
        ClsClass cc = new ClsClass();
        cc.setName(cvo.getName());
        cc.setDesc(cvo.getDesc());
        cc.setImgUrl(url);
        cc.setFrequency(cvo.getFrequency());
        cc.setRecommended(cvo.getRecommended());
        cc.setSeqNum(cvo.getSeqNum());
        cc.setType(cvo.getType());
        try {
            classDao.insert(cc);

        }catch (Exception ec){
            System.out.println(ec.getMessage());
        }
        return true;
    }
    public String uploadImage(MultipartFile image){
		//将图片保存到右拍云
				String path = null;
				try {
					if(image != null && !image.isEmpty()){
						Integer lastIndex = image.getOriginalFilename().lastIndexOf(".");
						String postfix = image.getOriginalFilename().substring(lastIndex);
						String fileName = UUID.randomUUID().toString()+postfix;
						 path = UploadImgUtil.uploadImg(image.getBytes(), fileName);
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
				return path;
	}
    public boolean editClass(MultipartFile file,ClsClassVo cvo){
    	String url = uploadImage(file);
        ClsClass cc = new ClsClass();
        cc.setId(cvo.getId());
        cc.setName(cvo.getName());
        cc.setDesc(cvo.getDesc());
        if(url != null){
        	cc.setImgUrl(url);
        }
        cc.setRecommended(cvo.getRecommended());
        cc.setFrequency(cvo.getFrequency());
        cc.setSeqNum(cvo.getSeqNum());
        cc.setType(cvo.getType());
        classDao.update(cc);
        return true;
    }

    public boolean removeClass(ClsClassVo cvo){
        int count =classDao.destroy(cvo.getId());
        if (count>0){
            return true;
        }
        return false;
    }

    public List<ClsCourse> getCourseByClassId(int classId){
        ClsCourse cc = new ClsCourse();
        cc.setClsClassId(classId);
        List<ClsCourse> list = courseDao.findByColumns(cc);
        return list;
    }

    public boolean addCourse(ClsCourseVo ccvo){
        ClsCourse cc = new ClsCourse();
        cc.setName(ccvo.getName());
        cc.setDesc(ccvo.getDesc());
        cc.setClsClassId(ccvo.getClassId());
        courseDao.insert(cc);
        return true;

    }


    public boolean editCourse(ClsCourseVo ccvo){
        ClsCourse cc = new ClsCourse();
        cc.setName(ccvo.getName());
        cc.setDesc(ccvo.getDesc());
        cc.setClsClassId(ccvo.getClassId());
        cc.setId(ccvo.getId());
        courseDao.update(cc);
        return true;

    }

    public boolean removeCourse(ClsCourseVo ccvo){
        int count = courseDao.destroy(ccvo.getId());
        if(count>0){
            return true;
        }
        return false;
    }

    public List<ClsCourseVideo> getCourseVideo(int courseId){
        ClsCourseVideo ccv = new ClsCourseVideo();
        ccv.setClsCourseId(courseId);
        List<ClsCourseVideo> list = courseVedioDao.findByColumns(ccv);

        return list;
    }



    public boolean addCourseVideo(ClsCourseVideo ccvo){
        courseVedioDao.insert(ccvo);
        return true;

    }


    public boolean editCourseVideo(ClsCourseVideo ccvo){
        courseVedioDao.update(ccvo);
        return true;

    }

    public boolean removeCourseVideo(ClsCourseVideo ccvo){
        int count = courseVedioDao.destroy(ccvo.getId());
        if(count>0){
            return true;
        }
        return false;
    }


    public List<ClsGate> getGateList(int courseId){
        ClsGate cg = new ClsGate();
        cg.setClsCourseId(courseId);
        List<ClsGate> list = gateDao.findByColumns(cg);
        return list;
    }

    public boolean addGate(ClsGate cg){
        gateDao.insert(cg);
        return true;
    }

    public boolean editGate(ClsGate cg){
        gateDao.update(cg);
        return true;
    }

    public boolean removeGate(ClsGate cg){
        int count = gateDao.destroy(cg.getId());
        if (count>0){
            return true;
        }
        return false;
    }


    public List<ClsWord> getWordList(int gateId){
        ClsWord cw = new ClsWord();
        cw.setClsGateId(gateId);
        List<ClsWord> list = wordDao.findByColumns(cw);
        return list;
    }


    public boolean addWord(ClsWord cw){
        wordDao.insert(cw);
        return true;
    }

    public boolean editWord(ClsWord cw){
        wordDao.update(cw);
        return true;
    }

    public boolean removeWord(ClsWord cw){
        int count = wordDao.destroy(cw.getId());
        if (count>0){
            return true;
        }
        return false;
    }

    public List<ClsGateSentence> getGateSentenceList(int gateId){
        List<ClsGateSentence> list = clsGateSentenceDao.findGateSentenceByGateId(gateId);
        return list;
    }

    public boolean addGateSentence(ClsGateSentence cw){
        clsGateSentenceDao.insert(cw);
        return true;
    }

    public boolean editGateSentence(ClsGateSentence cw){
        clsGateSentenceDao.update(cw);
        return true;
    }

    public boolean removeGateSentence(ClsGateSentence cw){
        int count = clsGateSentenceDao.destroy(cw.getId());
        if (count>0){
            return true;
        }
        return false;
    }

    public Pager getSentenceList(String sentence,String code,int page,int rows){
        Pager pager = sentenceDao.findSentenceByArgs(sentence,code,page,rows);
        return pager;
    }


    public boolean addSentence(ClsSentence cw){
        sentenceDao.insert(cw);
        return true;
    }

    public boolean editSentence(ClsSentence cw){
        sentenceDao.update(cw);
        return true;
    }

    public boolean removeSentence(ClsSentence cw){
        int count = sentenceDao.destroy(cw.getId());
        if (count>0){
            return true;
        }
        return false;
    }
    
    public void saveCoursePrize(ClsCoursePrize coursePrize) {
        coursePrizeDao.insert(coursePrize);
    }
    
    public ClsCoursePrize findCoursePrize(int userId, int classId, int courseId) {
        ClsCoursePrize entity = new ClsCoursePrize();
        entity.setClsClassId(classId);
        entity.setClsCourseId(courseId);
        entity.setUserId(userId);
        List<ClsCoursePrize> prizes = coursePrizeDao.findByColumns(entity);
        return prizes.size() > 0 ? prizes.get(0) : null;
    }
    
//    public void saveClassPrize(ClsClassPrize classPrize) {
//        classPrizeDao.insert(classPrize);
//    }
//    public void saveAchievementBonusRecord(BonusClassAchievementRecord bonusClassAchievementRecord) {
//        clsAchievementBonusRecordDao.insert(bonusClassAchievementRecord);
//    }
//    
////    public ClsClassPrize findClassPrize(int userId, int classId, int achievement) {
////        ClsClassPrize entity = new ClsClassPrize();
////        entity.setClsClassId(classId);
////        entity.setAchievement(achievement);
////        entity.setUserId(userId);
////        List<ClsClassPrize> prizes = classPrizeDao.findByColumns(entity);
////        return prizes.size() > 0 ? prizes.get(0) : null;
////    }
//    
//    public BonusClassAchievementRecord findAchievementBonusRecord(int userId, int classId, int achievement) {
//        BonusClassAchievementRecord entity = new BonusClassAchievementRecord();
//        entity.setClsClassId(classId);
//        entity.setAchievement(achievement);
//        entity.setUserId(userId);
//        List<BonusClassAchievementRecord> records = clsAchievementBonusRecordDao.findByColumns(entity);
//        return records.size() > 0 ? records.get(0) : null;
//    }
//    
//    public List<BonusClassAchievementRecordVo> findAchievementByUserId(int userId) {
//        return clsAchievementBonusRecordDao.findAchievementBonusRecordVos(userId);
//    }
    
    public List<Integer> findPrizeCourse(int classId, int userId) {
        return scoreDao.findPrizeCourse(classId, userId);
    }
    
//    public boolean finished(int classId, int userId) {
//        return scoreDao.finished(classId, userId);
//    }

	public List<ClsSentenceVo> findPCSentencesByGateId(Integer gateId) {
		return sentenceDao.findPCSentencesByGateId(gateId);
	}

	public List<ClsClassVo> finAllClassesOnlyForecast() {
		return classDao.findAllWithUserCountOnlyForecast();
	}
    
}
